package com.fingard.dsp.bank.directbank.cgbunion01.util;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;


public class MD5Utils {
	
	public static String getMD5(byte[] bytes) throws Exception {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(bytes, 0, bytes.length);
			byte tmp[] = md5.digest();
			return MD5Utils.byte2Hex(tmp);
		}catch(Exception e) {
			throw e;
		}
	}
	
	
	
	public static String getMD5(String filePath) throws Exception {
		FileInputStream inputStream = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			// String path = MD5Utils.class.getClassLoader().getResource("").getPath();
			File file = new File(filePath);
			inputStream = new FileInputStream(file);
			byte[] buffer = new byte[8192];
			int length;
			while((length = inputStream.read(buffer)) != -1) {
				md5.update(buffer, 0, length);
			}
			byte tmp[] = md5.digest();
			return MD5Utils.byte2Hex(tmp);
		}catch(Exception e) {
			throw e;
		} finally {
			IOUtils.closeQuietly(inputStream);
		}
	}
	
	public static String getStringMD5(String str) throws Exception {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(str.getBytes());
			byte tmp[] = md5.digest();
			return MD5Utils.byte2Hex(tmp);
		}catch(Exception e) {
			throw e;
		}
	}
	
	public static String byte2Hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp;
		for (int i = 0; i < b.length; i++) {
			stmp = Integer.toHexString(b[i] & 0xFF).toUpperCase();
			if (stmp.length() == 1) {
				hs.append("0").append(stmp);
			} else {
				hs.append(stmp);
			}
		}
		return hs.toString();
	}
}
